#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "../Sock/Socket.hpp"
#include "../Sock/errno.hpp"
#include "../Sock/Logmessage.hpp"
#include <pthread.h>
namespace onlineClient
{
    class Client
    {
        std::string ip_;
        uint16_t  port_;
        int sockfd_;
        pthread_t readTid_;//负责读取来自服务端的消息
    public:
        Client(const std::string& ip,const uint16_t port)
            :ip_(ip),port_(port),sockfd_(-1)
        {}

        void init()
        {
            sockfd_=Socket::CreateSock();
        }

        void run()
        {
            if(Socket::Connect(sockfd_,ip_,port_)!=0)
            {
                logMessage(WARNING,"connect err...");
            }

            serverIO();
        }
        ~Client()
        {
            if(sockfd_>=0)
                close(sockfd_);
        }
    private:
        void serverIO()
        {
            //创建一个线程，单独负责读消息
            pthread_create(&readTid_,nullptr,readMessage,(void*)&sockfd_);
            std::string msg;
            while (true)
            {
                // fprintf(stderr,"Enter# ");
                // fflush(stderr);
                getline(std::cin,msg);
                msg[msg.size()]=0;
                send(sockfd_,msg.c_str(),msg.size(),0);
            }
        }  

        static void *readMessage(void *args)
        {
            int sock = *(static_cast<int *>(args));
            pthread_detach(pthread_self());
            while (true)
            {
                char buffer[1024];
                size_t n = recv(sock, buffer, sizeof(buffer) - 1, 0);
                if (n > 0)
                    buffer[n] = 0;
                else
                {
                    break;
                }    
                std::cout << buffer << std::endl;
            }
            return nullptr;
        }    
    };
}